package com.slipper.core.gson;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.slipper.exception.CommonException;
import com.slipper.util.DateUtil;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

public class UtilDateTypeAdapter extends TypeAdapter<Date> {
    @Override
    public java.util.Date read(JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
        } else {
            try {
                return DateUtil.parseDate(reader.nextString());
            } catch (ParseException e) {
                throw new CommonException("日期【" + reader.nextString() + "】转换出错！", e);
            }
        }
    }

    @Override
    public void write(JsonWriter writer, java.util.Date value) throws IOException {
        writer.value(value == null ? null : DateUtil.formatTime(value));
    }
}